package com.developer.platform.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.developer.platform.domain.UserRole;
import com.developer.platform.domain.repository.IUserRoleRepository;
import com.developer.platform.infrastructure.data.mapper.UserRoleMapper;
import java.util.List;
import org.springframework.stereotype.Repository;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Repository
public class UserRoleRepository implements IUserRoleRepository {

    private final UserRoleMapper userRoleMapper;

    public UserRoleRepository(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public void deleteByUserId(long userId) {
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId, userId);
        userRoleMapper.delete(lambdaQueryWrapper);
    }

    @Override
    public void save(List<UserRole> userRoles) {
        userRoles.forEach(userRoleMapper::insert);
    }

    @Override
    public void save(long userId, List<Long> roleIds) {
        this.deleteByUserId(userId);
        roleIds.forEach(roleId -> {
            userRoleMapper.insert(new UserRole(userId, roleId));
        });
    }

}
